#!/usr/bin/env python
# coding=utf8

import re
import os
import sys
import commands


# reg = r"#\s{0,}vhallEOF-.*-start\s*?\n([\s\S]*?)\s*?#\s{0,}vhallEOF-.*-end"
reg = r"#\s{0,}vhallEOF-.*-start\s*?\n([\s\S]*?)\s*?#\s{0,}vhallEOF-.*-end"
suffix = '.pre-commit'


def filterBlankLine(content):
    return "\n".join(
        filter(lambda c: c.strip() != "", content.split('\n')))


def gitIgnoreAdd():
    gitIgnorePath = './.gitignore'
    if not os.path.isfile(gitIgnorePath):
        writeFile(gitIgnorePath, "*.pre-commit")
        return

    content = readFile(gitIgnorePath)
    mathchRes = re.search('\*' + suffix, content, re.M | re.I)
    if not mathchRes:
        content = filterBlankLine(content) + "\n*" + suffix + "\n"
        writeFile(gitIgnorePath, content)


def removePlaceholderCode(file):
    """
    删除文件中占位符之间的代码
    """
    content = readFile(file)
    if not content:
        return False

    mathchList = re.findall(reg, content, re.M | re.I)

    newContent = content
    for item in mathchList:
        if item.strip():
            newContent = newContent.replace(item, "")

    if content != newContent:
        # 文件备份
        writeFile(file + suffix, content)

        writeFile(file, newContent)
        return True

    return False


def readFile(file):
    with open(file, mode='r') as fp:
        return fp.read()
    return ""


def writeFile(file, content):
    with open(file, mode='w') as fp:
        fp.write(content)


def gitAdd(changeFiles):
    for file in changeFiles:
        cmd = 'git add %s' % file
        os.system(cmd)


def getCommitFileCount():
    cmd = 'git diff --cached --name-status | wc -l'
    count = commands.getoutput(cmd)
    return int(count)


def getChangeFiles():
    changeFiles = list()
    cmd = '''git diff --cached --name-status | grep '.php$' | awk -F' ' '$1 !="D" && $1 !~/^R\d*/ {print $2}' | uniq'''

    files = commands.getoutput(cmd)
    if not files:
        return changeFiles

    for file in files.split('\n'):
        isMatch = removePlaceholderCode(file)
        if isMatch:
            changeFiles.append(file)

    return changeFiles


def printChangedFiles(changeFiles):
    if changeFiles:
        print("----------- change file list -----------")
        for file in changeFiles:
            print("\033[32m" + file + "\033[0m")

        print("")


def recoveryFiles(changeFiles):
    """
    将备份的文件恢复
    """
    for file in changeFiles:
        os.system("rm -f %s && mv %s%s %s" % (file, file, suffix, file))


def run():
    changeFiles = getChangeFiles()
    printChangedFiles(changeFiles)

    gitIgnoreAdd()
    gitAdd(changeFiles)

    count = getCommitFileCount()
    recoveryFiles(changeFiles)
    if count == 0:
        print("\033[31mcommit stop, nothing to commit, working tree clean\033[0m")
        sys.exit(1)
    sys.exit(0)


if __name__ == "__main__":
    run()
